package com.yanyeori.framework.datasource.strategy;

import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 集合策略-轮询
 *
 * @author chenkuan 2021/8/19
 */
public class ListPollStrategy implements ListStrategy {

    private final Map<Object, Integer> map = new ConcurrentHashMap<>();

    @Override
    public <T> T get(List<T> list, Object arg) {
        if (CollectionUtils.isEmpty(list)) return null;
        int size = list.size();
        if (size == 1) return list.get(0);
        Integer num = map.getOrDefault(arg, 0);
        if (num >= size) num = 0;
        T t = list.get(num);
        map.put(arg, ++num);
        return t;
    }
}
